package database;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class GUIupdate extends JFrame {
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
    private static final String DATABASE_USER = "root";
    private static final String DATABASE_PASSWORD = "123456";
    Map<String, String> Mapping1,Mapping2,Mapping3,Mapping4,Mapping5;
    private JTable table;
    private DefaultTableModel tableModel;
    private JTextField tableNameTextField;

    // 映射数据库列名到显示名称
    private Map<String, String> columnDisplayNames;

    public GUIupdate() {
        setTitle("数据更新");
        setSize(800, 600);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        tableModel = new DefaultTableModel();
        table = new JTable(tableModel);

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        JPanel topPanel = new JPanel(new BorderLayout());
        tableNameTextField = new JTextField();
        JButton fetchButton = new JButton("Fetch Data");
        fetchButton.addActionListener(e -> fetchDataAndFillTable());

        topPanel.add(new JLabel("Table Name:"), BorderLayout.WEST);
        topPanel.add(tableNameTextField, BorderLayout.CENTER);
        topPanel.add(fetchButton, BorderLayout.EAST);

        add(topPanel, BorderLayout.NORTH);

        JButton updateButton = new JButton("Update Row");
        updateButton.addActionListener(e -> showUpdateDialog());

        add(updateButton, BorderLayout.SOUTH);
    }

    private void fetchDataAndFillTable() {
        String tableName = tableNameTextField.getText().trim();
        if (tableName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please enter a table name.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try (Connection connection = DriverManager.getConnection(DATABASE_URL, DATABASE_USER, DATABASE_PASSWORD)) {
            String query = "SELECT * FROM " + tableName;
            try (Statement statement = connection.createStatement();
                 ResultSet resultSet = statement.executeQuery(query)) {

                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();

                // 设置表头
                tableModel.setColumnCount(0);
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    String displayName = columnDisplayNames.getOrDefault(columnName, columnName);
                    tableModel.addColumn(displayName);
                }

                // 填充数据
                tableModel.setRowCount(0);
                while (resultSet.next()) {
                    Object[] rowData = new Object[columnCount];
                    for (int i = 1; i <= columnCount; i++) {
                        rowData[i - 1] = resultSet.getObject(i);
                    }
                    tableModel.addRow(rowData);
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "Failed to fetch data: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void showUpdateDialog() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "Please select a row to update.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        String tableName = tableNameTextField.getText().trim();
        if (tableName.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please enter a table name.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog updateDialog = new JDialog(this, "Update Row", true);
        updateDialog.setLayout(new GridLayout(tableModel.getColumnCount() + 1, 2));

        JTextField[] textFields = new JTextField[tableModel.getColumnCount()];
        for (int i = 0; i < tableModel.getColumnCount(); i++) {
            String columnName = tableModel.getColumnName(i);
            String actualColumnName = getActualColumnName(columnName);

            updateDialog.add(new JLabel(columnName));
            textFields[i] = new JTextField(tableModel.getValueAt(selectedRow, i).toString());
            updateDialog.add(textFields[i]);
        }

        JButton doneButton = new JButton("Done");
        doneButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try (Connection connection = DriverManager.getConnection(DATABASE_URL, DATABASE_USER, DATABASE_PASSWORD)) {
                    // Build the update SQL dynamically based on the table structure
                    StringBuilder sql = new StringBuilder("UPDATE " + tableName + " SET ");
                    for (int i = 1; i < tableModel.getColumnCount(); i++) {
                        String columnName = getActualColumnName(tableModel.getColumnName(i));
                        sql.append(columnName).append(" = ?, ");
                    }
                    sql.setLength(sql.length() - 2); // Remove last comma and space
                    String idColumnName = getActualColumnName(tableModel.getColumnName(0));
                    sql.append(" WHERE ").append(idColumnName).append(" = ?");

                    try (PreparedStatement statement = connection.prepareStatement(sql.toString())) {
                        for (int i = 1; i < tableModel.getColumnCount(); i++) {
                            statement.setObject(i, textFields[i].getText());
                        }
                        statement.setObject(tableModel.getColumnCount(), tableModel.getValueAt(selectedRow, 0));

                        System.out.println("Executing SQL: " + statement.toString()); // Debugging line

                        int rowsUpdated = statement.executeUpdate();

                        if (rowsUpdated > 0) {
                            JOptionPane.showMessageDialog(updateDialog, "Update successful!");
                            fetchDataAndFillTable(); // Refresh table data
                            updateDialog.dispose();
                        } else {
                            JOptionPane.showMessageDialog(updateDialog, "Update failed.", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(updateDialog, "Update failed: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        updateDialog.add(doneButton);
        updateDialog.pack();
        updateDialog.setLocationRelativeTo(this);
        updateDialog.setVisible(true);
    }

    private String getActualColumnName(String displayName) {
        for (Map.Entry<String, String> entry : columnDisplayNames.entrySet()) {
            if (entry.getValue().equals(displayName)) {
                return entry.getKey();
            }
        }
        return displayName; // 如果没有找到映射，则返回显示名称本身
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GUIupdate editor = new GUIupdate();
            editor.setVisible(true);
        });
    }
    private Map<String, String> empolyeeMapping() {
        Map<String, String> map = new HashMap<>();
        map.put( "员工编号Eid", "Eid");
        map.put("员工姓名Ename", "Ename");
        map.put("员工级别Elevel", "Elevel");
        map.put( "员工电话EtelPhone", "EtelPhone");
        map.put( "员工薪水ESalary", "ESalary");
        return map;
    }

    private Map<String, String> goodMapping() {
        Map<String, String> map = new HashMap<>();
        map.put("商品编号Gid", "Gid");
        map.put("商品名称GName", "GName");
        map.put("商品单价Gpay", "Gpay");
        map.put("商品编号Cid", "Cid");
        map.put("商品简介GIntroduction", "GIntroduction");
        return map;
    }
    private Map<String, String> customerMapping() {
        Map<String, String> map = new HashMap<>();
        map.put("客户编号Cid","Cid");
        map.put("客户名称CcompanyName","CcompanyName");
        map.put("商品简称CcompanySName","CcompanySName");
        map.put("地址CcompanyAddress","CcompanyAddress");
        map.put("公司电话CcompanyPhone","CcompanyPhone");
        map.put("邮件Cemail","Cemail");
        map.put("联系人Cname","Cname");
        map.put("联系人电话CtelPhone","CtelPhone");
        return map;
    }
    private Map<String, String> paymainMapping() {
        Map<String, String> map = new HashMap<>();
        map.put("采购清单Pid", "Pid");
        map.put("员工编号Eid", "Eid");
        map.put("采购数量Pcount", "Pcount");
        map.put("采购总价Ptotal", "Ptotal");
        map.put("采购时间Pdate", "Pdate");
        return map;
    }
    private Map<String, String> paydetailMapping() {
        Map<String, String> map = new HashMap<>();
        map.put("采购明细PDid", "PDid");
        map.put("采购清单Pid", "Pid");
        map.put("商品编号Gid", "Gid");
        map.put("采购数量Pcount", "Pcount");
        map.put("商品单价GPay", "GPay");
        map.put("商品总价total", "Total");
        return map;
    }
}

